<?php
namespace lib;
use lib\GlobalState;
class Auth {
    protected $db_prefix;
    protected $sys_key;
    protected $password_hash;
    protected $globalState;
    public function __construct($password_hash = null) {
        $this->db_prefix = dbconfig['sqlname'];
        $this->sys_key = SYS_KEY;
        $this->password_hash = $password_hash;
    }
    
    public function validateAdminLogin($token) {
        if(!$token) return ['status' => -1, 'data' => null];
        
        try {
            $decoded = aes256auth($token, $this->sys_key, 'DECODE');
            list($user, $sid, $expiretime) = explode("\t", $decoded);
            
            if($expiretime < time()) {
                return ['status' => -1, 'data' => null];
            }
            
            $sql = "SELECT * FROM `{$this->db_prefix}admin` WHERE `user` = :user LIMIT 1";
            $result = safeSqlQuery($sql, ['user' => $user]);
            
            if(empty($result['result'])) {
                return ['status' => -1, 'data' => null];
            }
            
            $admin = $result['result'][0];
            $session = md5($admin['user'] . $admin['pwd'] . $this->password_hash);
            
            if($session !== $sid) {
                return ['status' => -1, 'data' => null];
            }
            
            return ['status' => 1, 'data' => $admin];
        } catch(Exception $e) {
            return ['status' => -1, 'data' => null];
        }
    }
    
    public function validateUserLogin($token) {
        if(!$token) return ['status' => -1, 'data' => null];
        
        try {
            $decoded = aes256auth($token, $this->sys_key, 'DECODE');
            list($user, $sid, $expiretime) = explode("\t", $decoded);
            
            if($expiretime < time()) {
                return ['status' => -1, 'data' => null];
            }
            
            $sql = "SELECT * FROM `{$this->db_prefix}user` WHERE user=:user LIMIT 1";
            $result = safeSqlQuery($sql, ['user' => $user]);
            if(empty($result['result'])) {
                return ['status' => -1, 'data' => null];
            }
            
            $user = $result['result'][0];
            $session = md5($user['user'] . $user['pass'] . $this->password_hash .$user['salt']);
            
            if($session !== $sid) {
                return ['status' => -1, 'data' => null];
            }
            if($user['zt'] != 1){
                return ['status' => -1, 'data' => null];
            }
            
            return ['status' => 1, 'data' => $user];
        } catch(Exception $e) {
            return ['status' => -1, 'data' => null];
        }
    }
}